package com.itheima.health.config;


import com.itheima.health.userdetailservice.JWTAuthenticationFilter;
import com.itheima.health.userdetailservice.JWTAuthorizationFilter;
import com.itheima.health.userdetailservice.JwtProperties;
import com.itheima.health.userdetailservice.MyUserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
//  开启spring  security 权限注解
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableConfigurationProperties(JwtProperties.class)
public class MySecurityConfigurationAdpater extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailServiceImpl myUserDetailService;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //  数据库 认证和授权
        auth.userDetailsService(myUserDetailService).passwordEncoder(createPasswordEncoder());

        //  在内存中认证方法  和授权
        //    重写框架默认 账号和密码  - 内存版    比较明文  密码前面添加 {noop}
        //  密码  指定加密器对象 进行加密  xxx888xx000xx  加盐 因子     1233   密码
//        auth.inMemoryAuthentication().withUser("heima").password("{noop}1234").roles("admin")
//                .and().withUser("itcast").password("{noop}1234").roles("query");
//        System.out.println("密文1："+createPasswordEncoder().encode("1234"));
//        System.out.println("密文2："+createPasswordEncoder().encode("1234"));
//
//        SimpleGrantedAuthority grantedAuthority = new SimpleGrantedAuthority("QUERY");
//        SimpleGrantedAuthority grantedAuthority1 = new SimpleGrantedAuthority("UPDATE");
//        List<GrantedAuthority> list=new ArrayList<>();
//        list.add(grantedAuthority);
//        list.add(grantedAuthority1);
//
//        auth.inMemoryAuthentication().passwordEncoder(createPasswordEncoder())
//                .withUser("hjl").password(createPasswordEncoder().encode("1234"))
//                //   ROLE _  解析 角色    否则 解析成权限  使用  hasRole 解析注解
//                .roles("ADMIN")
//                .and()
//                .withUser("heima").password(createPasswordEncoder().encode("1234"))
//                //  使用hasAuthority解析注解
//                .authorities(list);
    }

    //   创建 密码加密器对象
    @Bean
    public PasswordEncoder createPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
                //  禁用CsrfFilter  禁止模拟跨域 发送token令牌
        http.csrf().disable().
                //转换前端发送json对象去认证  在认证成功之后创建token  响应给浏览器
                addFilter(new JWTAuthenticationFilter(super.authenticationManager(),jwtProperties))
                //对浏览器带的token解析 失败放过 回被后面鉴权拦截器拦截
                //解析成功 将username 和权限关键字放入上下文对象中
                .addFilter(new JWTAuthorizationFilter(super.authenticationManager(),jwtProperties))
                .sessionManagement()
                // 禁用session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);


        //  重写默认配置 1. 表单
        //  目标的登录页面
//        http.formLogin().loginPage("/login.html")
//                // 登录页面action 处理地址
//                .loginProcessingUrl("/login")
//                //  认证成功之后跳转的页面
//                .defaultSuccessUrl("/pages/index.html", false)
//                .failureUrl("/login.html")
//                .and()
//                //  用户 必须拥有  ADMIN角色才可以访问
//                .authorizeRequests()
//                .antMatchers("/pages/delete.html").hasRole("ADMIN")
//                .antMatchers("/pages/query.html").hasRole("QUERY")
//                .antMatchers("/pages/**").authenticated()
//                .and()
//                //  配置403  被拒绝 没有权限页面
//                .exceptionHandling().accessDeniedPage("/error.html")
//                .and()
//                //  退出     清除session 使失效session方法
//                .logout().logoutUrl("/logout").logoutSuccessUrl("/login.html").invalidateHttpSession(true)
//                .and()
//                //  禁用CsrfFilter  禁止模拟跨域 发送token令牌
//                .csrf().disable();
    }

//    @Override
//    public void configure(WebSecurity web) throws Exception {
//        //放过访问静态资源
//        web.ignoring().antMatchers("/css/**", "/js/**", "/img/**");
//    }
}
